import React, { useRef, useEffect } from "react";
import { forEach } from 'lodash-es'
import ReactECharts from 'echarts-for-react'

let barName1 = "类型1";

const echartsSize = (size, defalteWidth = 1920) => {
    let clientWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
    if (!clientWidth) return size
    let scale = (clientWidth / defalteWidth)
    return Number((size * scale).toFixed(3))
}

const Chart3 = React.memo(() => {
    const testRef = useRef(null)
    const testRef2 = useRef(null)

    useEffect(() => {
        addEventListener('resize', () => {
            console.log("%c Line:21 🥤 testRef2.current", "color:#fca650", testRef2.current);
            console.log("%c Line:22 🥟 echartsSize(18)", "color:#93c0a4", echartsSize(18));
            const option = setCurOption(testRef2.current.barName, testRef2.current.lineName);
            testRef.current.getEchartsInstance().setOption(option)
        })
    }, [])

    /**
    * 曲线图数据对象
    **/
    const lineData = (names) => {
        let lines = new Object();
        for (let i = 0; i < names.length; i++) {
            lines[names[i]] = new Object();
            lines[names[i]]["seriesData"] = randomData();
        }
        return lines;
    }

    /**
     * 曲线图数据源
     **/
    const randomData = () => {
        let data = [];
        let max = 80;
        let min = 5;
        for (let i = 0; i < 24; i++) {
            data.push(Math.floor(Math.random() * (max - min + 1) + min))
        }
        return data;
    }

    /**
     * 设备数据对象
     **/
    const rankData = (soName, count) => {
        let nameBar = [],
            valueBar = [];
        let max = 80;
        let min = 5;
        for (let i = 1; i < count + 1; i++) {
            let value = Math.floor(Math.random() * (max - min + 1) + min);
            let color = "#52c41a";
            if (value >= 70) {
                color = '#ff4d4f';
            } else if (value >= 30 && value < 70) {
                color = '#faad14';
            } else if (value > 0 && value < 30) {
                color = '#52c41a';
            }
            valueBar.push({
                value: value,
                name: `${soName}-来源点${i}`,
                visualMap: false,
                itemStyle: {
                    color: color,
                },
            })
        }
        valueBar.sort((a, b) => {
            return b.value - a.value
        })
        let values = valueBar.slice(0, 11)
        forEach(values, (value) => {
            nameBar.push(value.name)
        })
        return {
            name: nameBar.reverse(),
            value: values.reverse()
        }
    }

    let t1 = rankData("类型1", 7),
        t2 = rankData("类型2", 11),
        t3 = rankData("类型3", 9);

    let obj = {
        "类型1": {
            name: '类型1',
            visualMap: false,
            value: 7,
            soName: t1.name,
            soValue: t1.value,
            lineData: lineData(t1.name)
        },
        "类型2": {
            name: '类型2',
            visualMap: false,
            value: 11,
            soName: t2.name,
            soValue: t2.value,
            lineData: lineData(t2.name)
        },
        "类型3": {
            name: '类型3',
            visualMap: false,
            value: 9,
            soName: t3.name,
            soValue: t3.value,
            lineData: lineData(t3.name)
        }
    }

    const setCurOption = (barName, lineName) => {
        console.log("%c Line:106 🥥 obj[barName][lineName].seriesData", "color:#ea7e5c", obj[barName]["lineData"][lineName]?.seriesData);
        return {
            title: [{
                text: "数据来源类型数量统计",
                x: '25%',
                y: '3%',
                textAlign: 'center',
                textBaseline: 'middle',
                textStyle: {
                    fontSize: echartsSize(18)
                }
            }, {
                text: `${barName}来源点耗时`,
                x: '75%',
                y: '2%',
                textAlign: 'center',
                textBaseline: 'middle',
                textStyle: {
                    fontSize: 18
                }
            }, {
                text: `${lineName}-各时间点耗时`,
                x: '45%',
                y: '42%',
                textAlign: 'center',
                textBaseline: 'middle',
                textStyle: {
                    fontSize: 18
                }
            }],
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            legend: [{
                data: ['类型1', '类型2', '类型3'],
                x: 'left',
                orient: 'vertical'
            }],
            grid: [{
                left: '48%',
                right: '5%',
                top: '5%',
                bottom: '65%',
                containLabel: true
            },
            {
                gridindex: 1,
                left: '0%',
                right: '5%',
                top: '50%',
                bottom: '20%',
                containLabel: true
            }
            ],
            visualMap: {
                show: false,
                pieces: [{
                    gt: 0,
                    lt: 30,
                    color: '#52c41a'
                }, {
                    gte: 30,
                    lt: 70,
                    color: '#faad14'
                }, {
                    gte: 70,
                    color: '#ff4d4f'
                }]
            },
            xAxis: [{
                type: 'value',
                boundaryGap: [0, 0.01]
            },
            {
                gridIndex: 1,
                type: 'category',
                boundaryGap: false,
                data: ['0时', '1时', '2时', '3时', '4时', '5时', '6时', '7时', '8时', '9时', '10时', '11时', '12时', '13时', '14时', '15时', '16时', '17时', '18时', '19时', '20时', '21时', '22时', '23时']
            }
            ],
            yAxis: [{
                type: 'category',
                data: obj[barName].soName,
                axisLabel: {
                    interval: 0
                }
            },
            {
                gridIndex: 1,
                type: 'value',
            }
            ],
            series: [{
                name: '数量',
                type: 'pie',
                center: ['25%', '18%'],
                radius: ['15%', '20%'],
                label: {
                    formatter: '{b} : {c} ({d}%)'
                },
                data: [obj['类型1'], obj['类型2'], obj['类型3']]
            }, {
                name: 'top10',
                type: 'bar',
                label: {
                    show: true,
                    position: 'right',
                    color: "#00cfff"
                },
                data: obj[barName].soValue
            }, {
                xAxisIndex: 1,
                yAxisIndex: 1,
                name: lineName,
                type: 'line',
                data: obj[barName]["lineData"][lineName]?.seriesData,
                markPoint: {
                    data: [{
                        type: 'max',
                        name: '最大值',
                        symbolSize: 45
                    },
                    {
                        type: 'min',
                        name: '最小值',
                        symbolSize: 40
                    }
                    ],
                },
                markLine: {
                    data: [{
                        type: 'average',
                        name: '平均值'
                    }]
                }
            }]
        }
    }

    const onChartClick = (params) => {
        if (params.seriesType === "pie") {
            barName1 = params.name
            testRef.current.getEchartsInstance().clear()
            const option = setCurOption(barName1, obj[barName1].soName[obj[barName1]?.soName?.length - 1]);
            testRef2.current = {
                barName: barName1,
                lineName: obj[barName1].soName[obj[barName1]?.soName?.length - 1],
                clickType: "pie"
            }
            testRef.current.getEchartsInstance().setOption(option);
        }

        if (params.seriesType === "bar") {
            const option = setCurOption(barName1, params.name)
            testRef2.current = {
                barName: barName1,
                lineName: params.name,
                clickType: "bar"
            }
            testRef.current.getEchartsInstance().setOption(option);
        }
    }

    const onEvents = {
        'click': onChartClick,
    }

    testRef2.current = {
        barName: barName1,
        lineName: obj[barName1].soName[obj[barName1]?.soName?.length - 1],
        clickType: ""
    }

    return (
        <>
            <ReactECharts ref={testRef} option={setCurOption(barName1, obj[barName1].soName[obj[barName1]?.soName?.length - 1])} style={{ height: 700 }}
                onEvents={onEvents} notMerge={true} />
        </>
    );
})

export default Chart3